package com.dog.view.converter;

import com.dog.model.Role;
import com.dog.service.IRoleService;
import com.dog.spring.ServiceFactory;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;

/**
 * User: Kuttubek Aidaraliev
 * Date: 08.05.2010
 * Time: 9:03:56
 */
public class RoleConverter implements Converter {

    @Override
    public Object getAsObject(FacesContext facesContext, UIComponent uiComponent, String s) {
        IRoleService roleService = ServiceFactory.getRoleService();
        System.out.println(roleService + " " + s);
        Role role = null;
        try {
            role = roleService.get(new Long(s));
        } catch (Exception e){
            FacesMessage facesMessage = new FacesMessage("Conversation error occurred. ",
                    "Invalid Role selected. ");
            facesMessage.setSeverity(FacesMessage.SEVERITY_ERROR);
            throw new ConverterException(facesMessage);
        }
        if(role == null){
            FacesMessage facesMessage = new FacesMessage("Conversation error occurred. ",
                        "Role not found. ");
            facesMessage.setSeverity(FacesMessage.SEVERITY_ERROR);
            throw new ConverterException(facesMessage);
        }

        return role;

    }

    @Override
    public String getAsString(FacesContext facesContext, UIComponent uiComponent, Object o) {

        if(o instanceof Role) {
            Role role = (Role)o;
            return role.getId().toString();
        }
        else throw new IllegalArgumentException("Argument must be Role object!");
    }

}
